package com.business_clean.app.uitl;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.business_clean.ui.activity.project.AddCompanyProjectActivity;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.engine.CropEngine;
import com.luck.picture.lib.engine.CropFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.interfaces.OnQueryDataSourceListener;
import com.luck.picture.lib.interfaces.OnQueryFilterListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.style.SelectMainStyle;
import com.luck.picture.lib.style.TitleBarStyle;
import com.luck.picture.lib.utils.DateUtils;
import com.luck.picture.lib.utils.StyleUtils;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropImageEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import me.hgj.mvvmhelper.base.Ktx;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;
import top.zibin.luban.OnRenameListener;

/**
 * 全部增加压缩机制
 */
public class ChoosePicUtil {

    /**
     * 相机拍照
     */
    public static void openCameraTake(Context context) {
        PictureSelector.create(context)
                .openCamera(SelectMimeType.ofImage())
                .setCompressEngine(new ImageFileCompressEngine())
                .forResultActivity(PictureConfig.REQUEST_CAMERA);
    }

    public static void openCameraTake(Context context, OnResultCallbackListener<LocalMedia> listener) {
        PictureSelector.create(context)
                .openCamera(SelectMimeType.ofImage())
                .setCompressEngine(new ImageFileCompressEngine())
                .forResult(listener);
    }

    public static void openCameraCropTake(Context context, OnResultCallbackListener<LocalMedia> listener) {
        PictureSelector.create(context)
                .openCamera(SelectMimeType.ofImage())
                .setCropEngine(new ChoosePicUtil.ImageFileCropEngine())
                .setCompressEngine(new ImageFileCompressEngine())
                .forResult(listener);
    }

    /**
     * 打开相册
     */
    public static void openAlbum(Context context, int maxNum) {
        PictureSelector.create(context)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setCompressEngine(new ImageFileCompressEngine())
                .isPageSyncAlbumCount(true)
                .setQueryFilterListener(new OnQueryFilterListener() {
                    @Override
                    public boolean onFilter(LocalMedia media) {
                        return false;
                    }
                })
                .isDisplayCamera(false)
                .setMaxSelectNum(maxNum)
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }


    /**
     * 打开相册
     */
    public static void openAlbumCrop(Context context, int maxNum, OnResultCallbackListener<LocalMedia> listener) {
        PictureSelector.create(context)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setCropEngine(new ChoosePicUtil.ImageFileCropEngine())
                .setCompressEngine(new ImageFileCompressEngine())
                .isPageSyncAlbumCount(true)
                .setQueryFilterListener(new OnQueryFilterListener() {
                    @Override
                    public boolean onFilter(LocalMedia media) {
                        return false;
                    }
                })
                .isDisplayCamera(false)
                .setMaxSelectNum(maxNum)
                .forResult(listener);

    }

    /**
     * 打开相册
     */
    public static void openAlbum(Context context, int maxNum, OnResultCallbackListener<LocalMedia> listener) {
        PictureSelector.create(context)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setCompressEngine(new ImageFileCompressEngine())
                .isPageSyncAlbumCount(true)
                .setQueryFilterListener(new OnQueryFilterListener() {
                    @Override
                    public boolean onFilter(LocalMedia media) {
                        return false;
                    }
                })
                .isDisplayCamera(false)
                .setMaxSelectNum(maxNum)
                .forResult(listener);

    }


    /**
     * 自定义压缩
     */
    private static class ImageFileCompressEngine implements CompressFileEngine {

        @Override
        public void onStartCompress(Context context, ArrayList<Uri> source, OnKeyValueResultCallbackListener call) {
            Luban.with(context).load(source).ignoreBy(50).setRenameListener(new OnRenameListener() {
                @Override
                public String rename(String filePath) {
                    int indexOf = filePath.lastIndexOf(".");
                    String postfix = indexOf != -1 ? filePath.substring(indexOf) : ".jpg";
                    return DateUtils.getCreateFileName("CMP_") + postfix;
                }
            }).filter(new CompressionPredicate() {
                @Override
                public boolean apply(String path) {
                    if (PictureMimeType.isUrlHasImage(path) && !PictureMimeType.isHasHttp(path)) {
                        return true;
                    }
                    return !PictureMimeType.isUrlHasGif(path);
                }
            }).setCompressListener(new OnNewCompressListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onSuccess(String source, File compressFile) {
                    if (call != null) {
                        call.onCallback(source, compressFile.getAbsolutePath());
                    }
                }

                @Override
                public void onError(String source, Throwable e) {
                    if (call != null) {
                        call.onCallback(source, null);
                    }
                }
            }).launch();
        }
    }


    /**
     * 自定义裁剪
     */
    public static class ImageFileCropEngine implements CropFileEngine {

        @Override
        public void onStartCrop(Fragment fragment, Uri srcUri, Uri destinationUri, ArrayList<String> dataSource, int requestCode) {
            UCrop.Options options = buildOptions(fragment.getContext());
            UCrop uCrop = UCrop.of(srcUri, destinationUri, dataSource);
            uCrop.withOptions(options);
            uCrop.setImageEngine(new UCropImageEngine() {
                @Override
                public void loadImage(Context context, String url, ImageView imageView) {
                    if (!ImageLoaderUtils.assertValidRequest(context)) {
                        return;
                    }
                    Glide.with(context).load(url).override(180, 180).into(imageView);
                }

                @Override
                public void loadImage(Context context, Uri url, int maxWidth, int maxHeight, OnCallbackListener<Bitmap> call) {
                    Glide.with(context).asBitmap().load(url).override(maxWidth, maxHeight).into(new CustomTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                            if (call != null) {
                                call.onCall(resource);
                            }
                        }

                        @Override
                        public void onLoadCleared(@Nullable Drawable placeholder) {
                            if (call != null) {
                                call.onCall(null);
                            }
                        }
                    });
                }
            });
            uCrop.start(fragment.requireActivity(), fragment, requestCode);
        }
    }


    /**
     * 配制UCrop，可根据需求自我扩展
     *
     * @return
     */
    private static UCrop.Options buildOptions(Context context) {
        UCrop.Options options = new UCrop.Options();
        options.setHideBottomControls(true);//裁剪菜单栏
        options.setFreeStyleCropEnabled(false);//裁剪框or图片拖动
        options.setShowCropFrame(true);//裁剪边框
        options.setShowCropGrid(true);//网格
        options.setCircleDimmedLayer(false);//圆形头像裁剪框
        options.setCropOutputPathDir(getSandboxPath(context));
        options.withAspectRatio(1, 1);//图片的比例
        options.isCropDragSmoothToCenter(false);
        options.isForbidSkipMultipleCrop(true);
        options.setMaxScaleMultiplier(100);
        return options;
    }


    /**
     * 创建自定义输出目录
     *
     * @return
     */
    private static String getSandboxPath(Context context) {
        File externalFilesDir = context.getExternalFilesDir("");
        File customFile = new File(externalFilesDir.getAbsolutePath(), "Sandbox");
        if (!customFile.exists()) {
            customFile.mkdirs();
        }
        return customFile.getAbsolutePath() + File.separator;
    }

}
